package com.mad.game.controller;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

import com.mad.game.backend.GameDemo;


public class MainWndKeyController extends DefaultKeyController {

	public static final char LEFT = 'a',
							 RIGHT = 'd',
							 JUMP = 'w',
							 SPAWN = 's', 
							 PAUSE = 'p', 
							 SHOOT = 'e' ; 
	public static final int CAM_LEFT = KeyEvent.VK_LEFT,
							CAM_RIGHT = KeyEvent.VK_RIGHT; 
	
	public static final boolean INSTANT_EXIT = true ; 
	
	public static List<Character> PLAYER_CONTROLS ;
	public static List<Integer> CAMERA_CONTROLS ;
	static{ 
		if(PLAYER_CONTROLS == null){
			PLAYER_CONTROLS = new ArrayList<Character>();
			PLAYER_CONTROLS.add(LEFT);
			PLAYER_CONTROLS.add(RIGHT);
			PLAYER_CONTROLS.add(JUMP);
			PLAYER_CONTROLS.add(SPAWN);
			PLAYER_CONTROLS.add(PAUSE);
			PLAYER_CONTROLS.add(SHOOT);
		}
		if(CAMERA_CONTROLS == null){
			CAMERA_CONTROLS = new ArrayList<Integer>();
			CAMERA_CONTROLS.add(CAM_LEFT);
			CAMERA_CONTROLS.add(CAM_RIGHT);
		}
	}
	
	private boolean keyAlreadyTyped;

	public MainWndKeyController(JFrame wnd) {
		super(wnd);
	}

	@Override
	public void keyPressed(KeyEvent e) {		
		if (GameDemo.getGameInstance().isInGame() 
				&& !keyAlreadyTyped
				) {
			if(e.getKeyChar() == PAUSE){
				if(GameDemo.getGameInstance().isLevelPaused())
					GameDemo.getGameInstance().continueLevel();
				else
					GameDemo.getGameInstance().pauseLevel();
			}
			if(!GameDemo.getGameInstance().isLevelPaused()){
				if(	GameDemo.getGameInstance().doesPlayerExist()){
					// player controls 
					if(!GameDemo.getGameInstance().doesPlayerJump()){
						if (e.getKeyCode() == CAM_LEFT)
							GameDemo.getGameInstance().movePlayerLeft();
						else if (e.getKeyCode() == CAM_RIGHT)
							GameDemo.getGameInstance().movePlayerRight();
						if (e.getKeyChar() == JUMP && !GameDemo.getGameInstance().doesPlayerJump())
							GameDemo.getGameInstance().jumpPlayerStraightUp();
					}
					if(e.getKeyChar() == SHOOT)
						GameDemo.getGameInstance().playerShoot();
				}
				if(e.getKeyChar() == SPAWN)
					GameDemo.getGameInstance().spawnPlayer();
			}
			keyAlreadyTyped = true;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
			if(INSTANT_EXIT) GameDemo.getGameInstance().exitApplication(); 
			else GameDemo.getGameInstance().leaveGame();
			this.parentWnd.dispose();
		}
//		if(e.getKeyChar() == SPAWN)
//			GameDemo.getGameInstance().spawnPlayer();
		
		if(PLAYER_CONTROLS.contains(e.getKeyChar()) || CAMERA_CONTROLS.contains(e.getKeyCode())) 
			this.keyAlreadyTyped = false ; 
	}

	@Override
	public void keyTyped(KeyEvent e) {
		
	}

}
